﻿using UnityEngine.UI;
using UnityEngine;

public static class UnityExtension
{
    /// <summary>
    /// 查找子物体上的组件，多用于UI
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="parent"></param>
    /// <param name="path"></param>
    /// <returns></returns>
    public static T FindComponent<T>(this GameObject parent, string path = "") where T : class
    {
        var pathRoot = parent.transform.Find(path);
        if (pathRoot == null) { return null; }
        return pathRoot.GetComponent<T>();
    }

    public static T AddComponentIFNotExist<T>(this GameObject obj) where T : Component
    {
        var t = obj.GetComponent<T>();
        if (t == null)
        {
            t = obj.AddComponent<T>();
        }

        return t;
    }

    public static void SetText(this Button btn, string text)
    {
        btn.gameObject.FindComponent<Text>("Text").text = text;
    }

    public static string GetText(this Button btn)
    {
        return btn.gameObject.FindComponent<Text>("Text").text;
    }

    public static void SetText(this Toggle btn, string text)
    {
        btn.gameObject.FindComponent<Text>("Text").text = text;
    }

    public static string GetText(this Toggle btn)
    {
        return btn.gameObject.FindComponent<Text>("Text").text;
    }

    public static void DestoryAllChildren(this Transform parent)
    {
        for (int i = 0; i < parent.childCount; ++i)
        {
            GameObject.Destroy(parent.GetChild(i).gameObject);
        }
    }
}
